import fs from 'fs';
import path from 'path';
import { Logger } from '../../utils';

export function createRecordFile(sessionId: string) {
  const dirName = path.resolve(__dirname, `./output/${sessionId}`);
  if (!fs.existsSync(dirName)) {
    fs.mkdir(dirName, (err: any) => {
      if (err) {
        Logger.error(err);
      }
    });
  }
}

export function writeRecordFile({ sessionId, recordData }: { sessionId: string; recordData: string }) {
  const dirPath = path.resolve(__dirname, `./output/${sessionId}`);
  const fileList = fs.readdirSync(dirPath);
  const fileName = path.resolve(dirPath, `record-${fileList ? fileList.length : 0}`);
  fs.writeFile(fileName, recordData, (err: any) => {
    if (err) {
      Logger.error(err);
    }
  });
}

export function readRecordFile(sessionId: string) {
  return new Promise((resolve, reject) => {
    const dirPath = path.resolve(__dirname, `./output/${sessionId}`);
    if (!fs.existsSync(dirPath)) {
      Logger.error(`录制${sessionId}的文件不存在`);
      reject();
    } else {
      const fileList = fs.readdirSync(dirPath);
      const recordList: any[] = [];
      fileList.forEach((file) => {
        if (file.indexOf('record') > -1) {
          recordList.push(
            new Promise((reso, reje) => {
              fs.readFile(path.resolve(dirPath, file), 'utf8', (err, data) => {
                if (err) {
                  Logger.error(err);
                  reje();
                } else {
                  reso(data);
                }
              });
            }),
          );
        }
      });

      Promise.all(recordList).then((list) => {
        let records: string = '';

        list.forEach((element, index) => {
          if (!records && list.length - 1 == index) {
            records += element;
          } else if (records && index == list.length - 1) {
            records += element.replace(/\[/, ',');
          } else if (!records && index < list.length - 1) {
            records += element.replace(/(.*)]/, '$1');
          } else {
            records += element.replace(/\[/, ',').replace(/(.*)]/, '$1');
          }
        });
        resolve(records);
      });
    }
  });
}
